# # #
# send message, file trans and remote contral
# server
# axn  2020.08.26
# version 0.0.1

#!/usr/bin/python3

import os, socket
import threading        

buffSize=4096
help='''help: this help message
quit/q/exit: exit
get/down filename [path/rename]: download file [and rename]
send/up filename: upload file
m/message/msg: allow server send message
cmd: remote contral'''


def servFunc( cltSock,addr ):
    # msg='welcome to connection, type help for help'
    # addr=cltSock.getsockname()  +str(addr) 
    print('connection from {}' .format( addr ) )

    dir=homeDir
    # cltSock.send( msg .encode() )
    cltSock.send(f'Welcome to connect, {cltSock.getpeername()}\n\
    type help for help\n{dir}>>' .encode() )
    
    while True:
        
        recvMsg=cltSock.recv(1024).decode()
        print('message from {}{}'.format(addr,recvMsg)  )
        
        # 1.quit
        if recvMsg in ('q','quit','exit'):
            cltSock.send(b'Bye')
            print('{} is logout'.format(addr) )
            cltSock.close()
            # break
            return 0
        
        # 2.change directory
        elif not recvMsg.find('cd '):  # 'cd' in recvMsg and index=0  /// re.match('cd ',recvMsg)
            # dir=recvMsg.split(' ',1)[1]
            # if os.path.isdir:
            try:
                os.chdir(recvMsg[3:])
                dir=os.getcwd()
                cltSock.send(dir.encode()+b'>>')
            except Exception as err:
                cltSock.send(  f'{err}\n{dir}>>' .encode() )
        
        # 3.download file
        elif not (recvMsg.find('get ') and recvMsg.find('down ') ):
            print('asdada')
            fname=recvMsg.split(' ')[1]
            if os.path.isfile(fname):
                fsize=os.stat(fname).st_size
                cltSock.send(f'file size is {fsize}\r\n' .encode() )
            
                with open(fname,'rb') as fp:
                    txt=fp.read(buffSize)
                    while txt:
                        cltSock.send(txt)
                        txt=fp.read(buffSize)
                        
                # cltSock.send(b'200 ok')
                print('ok')
            else:
                print('not404')
                cltSock.send( f'file "{fname}" not found' .encode() )

        # elif recvMsg=='wait':
            
        
        # normal message
        else:
            print('qqqq')
            cltSock.send(f'{dir}>>>'.encode() )
            # pp=os.popen(recvMsg)
            # cltSock.send( pp.read().encode() )
        # return 1

# program start
servSock= socket.socket( socket.AF_INET, socket.SOCK_STREAM )

homeDir=os.getcwd()
tmp=input('输入host port，默认0.0.0.0 8000：')
if tmp:
    host,port=tmp.split(' ')
    port=int(port)
else:
    host=''
    port=8000
servSock.bind( (host,port) )

servSock.listen(1)

print('service is started on {}:{}\nwaiting for connection...'\
    .format(socket.gethostbyname(host),port))
# print(servSock.getsockname(), '1.1.1.1 80')
# print(socket.getfqdn(host),'desktop-name')
# print(socket.gethostname(),'0.0.0.0',socket.gethostbyname(host),'0.0.0.0')



while True:

    # sockacc=servSock.accept()
    # cltSock,addr=sockacc
    # threading.Thread( conHandle(), sockacc )
    threading.Thread( target=servFunc, args=servSock.accept() ).start()
    

# servSock.close()